import { useApi } from '@/composables/useApi';
import { useRouter } from 'vue-router';
import type { ApiResponse, Database } from '~/types/page-admin';


export const useAdminApi = () => {

  // 获取首页聚合数据
  const getAdminData = async (): Promise<Database> => {
    try {
      const response = await useApi<ApiResponse>('/api/page-admin', {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      console.log('Home data fetched successfully:', response)
      // 转换数据格式以适应前端组件
      return response.data
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }
  const updateHomeData = async (data: Database) => {
    try {
      const response = await useApi<ApiResponse>('/api/page-admin', {
        method: 'PUT',
        body: data,
        headers: {
          'Content-Type': 'application/json'
        },
      })

      if (response.success) {
        console.log('首页数据更新成功:', response)
        // 可以在这里添加成功通知
        return response
      }

      throw new Error(response.message || '更新失败')

    } catch (error) {
      console.error('更新首页数据失败:', error)
      throw error // 继续抛出错误以便外部处理
    }
  }

  const contactSubmit = async (formData: any) => {
    try {
      const response = await useApi<any>('/api/contact', {
        method: 'POST',
        body: JSON.stringify(formData),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      console.log('Form submitted successfully:', response)
      // 处理提交成功后的逻辑
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  return {
    getAdminData,
    updateHomeData,
  }
}